#!/usr/bin/env python
#
# Copyright (C) 2013 Anders Logg
#
# This file is part of DOLFIN.
#
# DOLFIN is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# DOLFIN is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with DOLFIN. If not, see <http://www.gnu.org/licenses/>.
#
# First added:  2013-02-26
# Last changed: 2013-02-26
#
# Plot growth of code as function of time. This script should be
# run rom the top level directory.

from commands import getoutput
from datetime import datetime
import pylab as pl

# Suffixes to check
suffixes = [".h", ".hh", ".cpp", ".C"]

# Paths to skip
skip = ["demo", "bench", "test", "local", "build"]

# Get time stamps
timestamps = getoutput("bzr log | grep timestamp | awk '{print $3}'")
t = []
for timestamp in timestamps.split("\n"):
    y, m, d = timestamp.split("-")
    t.append(datetime(int(y), int(m), int(d)))
t.reverse()

# Revisions to check
revisions = range(len(t))

# For quick testing
#revisions = revisions[-10:]
#t = t[-10:]

# Iterate over revisions
locs = []
for i, r in enumerate(revisions):

    print "Updating to revision %r %s" % (r, t[i])

    # Update repository
    getoutput("bzr update -r %d" % r)

    # Count the lines of code
    n_total = 0
    for suffix in suffixes:
        skips = " | ".join("grep -v %s" % s for s in skip)
        n = getoutput("""find . -name *%s \
                  | %s \
                  | xargs wc -l \
                  | grep total \
                  | awk '{print $1}'""" % (suffix, skips))
        if n.isdigit():
            n_total += int(n)

    # Store lines of code
    print "%d lines of code" % n_total
    locs.append(n_total)

# Store results to file
f = open("klocs.csv", "w")
f.write("\n".join("%d-%d-%d,%d" % \
                      (t[i].year, t[i].month, t[i].day, locs[i]) \
                      for i in range(len(revisions))))
f.close()

# Plot results
pl.plot(t, locs)
pl.grid(True)
pl.ylabel("Lines of code")
pl.title("Code growth for DOLFIN %d - %d" % (t[0].year, t[-1].year))
pl.show()
